package com.zengdada.authority.config.security.intercept;

import com.zengdada.authority.utils.HEXUtil;
import com.zengdada.authority.utils.JsonMessage;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

    private String userLogonPage;
    private boolean remember; // 是否记住上一次请求的页面

    /**
     * @param loginFormUrl URL where the login page can be found. Should either be
     *                     relative to the web-app context path (include a leading {@code /}) or an absolute
     *                     URL.
     */
    public MyLoginUrlAuthenticationEntryPoint(String loginFormUrl, boolean remember) {
        super(loginFormUrl);
        this.userLogonPage = loginFormUrl;
        this.remember = remember;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            try (PrintWriter out = response.getWriter()) {
                out.print(JsonMessage.fail("请登陆后重试！！", 1024).toJsonString());
            }
        } else {
//            super.commence(request, response, authException);
            String sreference = response.encodeURL(request.getRequestURI().substring(request.getContextPath().length()));
            String querString = request.getQueryString();
            String userLogonPageReal = userLogonPage, userLogonPageTemp = request.getContextPath() + userLogonPageReal;

            // 增加参数reference
            // 登录成功可跳转至该页面
            if (remember && request.getParameter("reference") == null) {
                userLogonPageTemp = String.format("%s%sreference=%s&loginCode=%s",
                        userLogonPageTemp,
                        userLogonPageReal.indexOf('?') != -1 ? "&" : "?",
                        HEXUtil.encrypt(querString != null ? String.format("%s?%s", sreference, querString) : sreference, "login_before_request", HEXUtil.CipherType.AES128),
                        1024
                );
            }
            response.sendRedirect(userLogonPageTemp);
        }

    }
}